package com.example.spring.proxy;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YangZhen
 * @date 2022/5/28 15:46
 * @since 1.0.0
 */
public class AccessorScannerRegistrar implements ImportBeanDefinitionRegistrar {

    private static final String BASE_PACKAGES = "basePackages";

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        List<String> basePackages = new ArrayList<>();
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(OpenapiScan.class.getName()));
        for (String pkg : attributes.getStringArray(BASE_PACKAGES)) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }

        if (!basePackages.isEmpty()) {
            ClassPathOpenapiScanner classPathOpenapiScanner = new ClassPathOpenapiScanner(registry);
            classPathOpenapiScanner.registerFilters();
            classPathOpenapiScanner.doScan(StringUtils.toStringArray(basePackages));
        }
    }
}
